package com.ruoyi.meter.service.impl;


import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.meter.domain.MeterLedger;
import com.ruoyi.meter.mapper.MeterLedgerMapper;
import com.ruoyi.meter.service.IMeterLedgerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 计量台账Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class MeterLedgerServiceImpl implements IMeterLedgerService {
    @Autowired
    private MeterLedgerMapper meterLedgerMapper;

    @Autowired
    protected Validator validator;


    /**
     * 查询计量台账
     *
     * @param projectId 计量台账主键
     * @return 计量台账
     */
    @Override
    public MeterLedger selectMeterLedgerByProjectId(Long projectId) {
        return meterLedgerMapper.selectMeterLedgerByProjectId(projectId);
    }

    /**
     * 添加查询数量
     * @param meterLedger
     * @return
     */
    @Override
    public MeterLedger selectMeterLedgerCountList(MeterLedger meterLedger) {
        return meterLedgerMapper.selectMeterLedgerCountList(meterLedger);
    }

    /**
     * 查询计量台账列表
     *
     * @param meterLedger 计量台账
     * @return 计量台账
     */
    @Override
    public List<MeterLedger> selectMeterLedgerList(MeterLedger meterLedger) {
        List<MeterLedger> meterLedgers = meterLedgerMapper.selectMeterLedgerList(meterLedger);
        meterLedgers.forEach(meterLedger1 -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (null == meterLedger1.getNextVerification() || "".equals(meterLedger1.getNextVerification())) {
                meterLedger1.setFree30("0");
            } else {
                Date date = null;
                try {
                    date = simpleDateFormat.parse(meterLedger1.getNextVerification());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Date dateNow = new Date();
                if("随大修".equals(meterLedger1.getEffect())){
                    meterLedger1.setFree30("0");
                    return;
                }
                //差额 现在时间-有效期
                int diff = (int) TimeUnit.DAYS.convert(dateNow.getTime() - date.getTime(), TimeUnit.MILLISECONDS);
                if (diff > 0) {
                    //超期
                    meterLedger1.setFree30("2");
                } else if (diff > -60) {
                    //两个月
                    meterLedger1.setFree30("1");
                } else {
                    //正常
                    meterLedger1.setFree30("0");
                }
            }
            updateMeterLedger(meterLedger1);
        });

        return meterLedgers;
    }

    /**
     * 新增计量台账
     *
     * @param meterLedger 计量台账
     * @return 结果
     */
    @Override
    public int insertMeterLedger(MeterLedger meterLedger) {
        meterLedger.setCreateTime(DateUtils.getNowDate());
        //todo 计算时间
        if (meterLedger.getLastVerification().length()==10) {
            int year = Integer.parseInt(meterLedger.getLastVerification().substring(0, 4));
            int month = Integer.parseInt(meterLedger.getLastVerification().substring(5, 7));
            int day = Integer.parseInt(meterLedger.getLastVerification().substring(8, 10));
            int cycle = Integer.parseInt(meterLedger.getVerificationCycle());
            LocalDate today = LocalDate.of(year, month, day);
            LocalDate DaysLater = today.plusDays(cycle);
            meterLedger.setNextVerification(DaysLater.toString());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (null == meterLedger.getNextVerification() || "".equals(meterLedger.getNextVerification())) {
                meterLedger.setFree30("0");
            } else {
                Date date = null;
                try {
                    date = simpleDateFormat.parse(meterLedger.getNextVerification());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Date dateNow = new Date();
                //差额 现在时间-有效期
                int diff = (int) TimeUnit.DAYS.convert(dateNow.getTime() - date.getTime(), TimeUnit.MILLISECONDS);
                if (diff > 0) {
                    //超期
                    meterLedger.setFree30("2");
                } else if (diff > -60) {
                    //两个月
                    meterLedger.setFree30("1");
                } else {
                    //正常
                    meterLedger.setFree30("0");
                }
            }
            return meterLedgerMapper.insertMeterLedger(meterLedger);
        } else {
            return meterLedgerMapper.insertMeterLedger(meterLedger);
        }
    }

    /**
     * 修改计量台账
     *
     * @param meterLedger 计量台账
     * @return 结果
     */
    @Override
    public int updateMeterLedger(MeterLedger meterLedger) {
        meterLedger.setUpdateTime(DateUtils.getNowDate());
        //todo 计算时间
        if (meterLedger.getLastVerification().length()==10) {
            int year = Integer.parseInt(meterLedger.getLastVerification().substring(0, 4));
            int month = Integer.parseInt(meterLedger.getLastVerification().substring(5, 7));
            int day = Integer.parseInt(meterLedger.getLastVerification().substring(8, 10));
            int cycle = Integer.parseInt(meterLedger.getVerificationCycle());
            LocalDate today = LocalDate.of(year, month, day);
            LocalDate DaysLater = today.plusDays(cycle);
            meterLedger.setNextVerification(DaysLater.toString());
            return meterLedgerMapper.updateMeterLedger(meterLedger);
        } else {
            return meterLedgerMapper.updateMeterLedger(meterLedger);
        }
    }
    public int updateMeterLedgerByFree1(MeterLedger meterLedger) {
        meterLedger.setUpdateTime(DateUtils.getNowDate());
        //todo 计算时间
        if (meterLedger.getLastVerification().length()==10) {
            int year = Integer.parseInt(meterLedger.getLastVerification().substring(0, 4));
            int month = Integer.parseInt(meterLedger.getLastVerification().substring(5, 7));
            int day = Integer.parseInt(meterLedger.getLastVerification().substring(8, 10));
            int cycle = Integer.parseInt(meterLedger.getVerificationCycle());
            LocalDate today = LocalDate.of(year, month, day);
            LocalDate DaysLater = today.plusDays(cycle);
            meterLedger.setNextVerification(DaysLater.toString());
            return meterLedgerMapper.updateMeterLedgerByFree1(meterLedger);
        } else {
            return meterLedgerMapper.updateMeterLedgerByFree1(meterLedger);
        }
    }

    /**
     * 导入计量台账
     *
     * @param meterLedger 计量台账
     * @return 结果
     */

    @Override
    public String importUser(List<MeterLedger> meterLedgerList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(meterLedgerList) || meterLedgerList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MeterLedger meterLedger : meterLedgerList) {
            setPerfect(meterLedger);
            try {
                // 验证是否存在这个用户
                MeterLedger meterLedger1 = meterLedgerMapper.selectMeterLedgerByFree1(meterLedger);
                if (StringUtils.isNull(meterLedger1)) {
//                    BeanValidators.validateWithException(validator, meterLedger1);
                    meterLedger.setCreateBy(operName);
                    this.insertMeterLedger(meterLedger);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + meterLedger.getProjectId() + " 导入成功");
                } else if (isUpdateSupport) {

                    meterLedger.setUpdateBy(operName);
                    this.updateMeterLedgerByFree1(meterLedger);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + meterLedger.getProjectId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、数据 " + meterLedger1.getProjectId() + " 已存在");
                }
            } catch (Exception e) {
                System.out.println(e.toString());
                failureNum++;
                String msg = "<br/>" + failureNum + "、数据 " + meterLedger.getProjectId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());

            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 批量删除计量台账
     *
     * @param projectIds 需要删除的计量台账主键
     * @return 结果
     */
    @Override
    public int deleteMeterLedgerByProjectIds(Long[] projectIds) {
        return meterLedgerMapper.deleteMeterLedgerByProjectIds(projectIds);
    }

    /**
     * 删除计量台账信息
     *
     * @param projectId 计量台账主键
     * @return 结果
     */
    @Override
    public int deleteMeterLedgerByProjectId(Long projectId) {
        return meterLedgerMapper.deleteMeterLedgerByProjectId(projectId);
    }

    public void setPerfect(MeterLedger meterLedger) {
        // 获取当前登录用户
        LoginUser usr = SecurityUtils.getLoginUser();

        meterLedger.setPerfect(usr.getUser().getNickName());
        Date currentDate = new Date();
        meterLedger.setPerfecttime(currentDate);
    }


}
